package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.pojo.Shopcart;
import com.example.demo.pojo.User;
import com.example.demo.service.ShopCartService;
import io.swagger.annotations.Api;


import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.security.auth.message.callback.SecretKeyCallback;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "购物车",tags = "购物车")
@RequestMapping(value = "/ShopCar",method = RequestMethod.POST)
public class ShopCartController {
    @Resource(name = "shopCartService")
    private ShopCartService shopCartService;
    Cookie userCookie;
    Cookie userCookieEr;
    @ApiOperation(value = "如果未登陆加入cookie,登陆以后保存数据库",notes = "如果未登陆加入cookie,登陆以后保存数据库")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(value = "数量",name = "shopNumber"),
                    @ApiImplicitParam(value = "商品id",name = "goodsId")
            }
    )
    @RequestMapping("/ShoppingCart")
    private String ShoppingCart(HttpSession session,int shopNumber,int goodsId){
       try{
           User user=(User) session.getAttribute("user");
           System.out.println(user.getName());
           if(user==null){
               String shopNumbera=String.valueOf(shopNumber);
               String goodsEr=String.valueOf(goodsId);
               userCookie =new Cookie("shopNumber",shopNumbera);
               userCookieEr =new Cookie("goodsEr",goodsEr);
           }else {
               Shopcart shopcart=new Shopcart();
                shopcart.setShopnumber(shopNumber);
                shopcart.setGoodsid(goodsId);
                shopcart.setUid(user.getUserid());
               int i= shopCartService.insertSelective(shopcart);
               System.out.println(i);

           }
           return JSON.toJSONString("保存数据库成功！");
       }catch (Exception e){
          return "未登陆";
       }

    }
    @ApiOperation(value = "按商品id删除购物车")
    @ApiImplicitParam(name = "shopingId",value = "商品id存到数组")
    @RequestMapping(value = "/delShop",method = RequestMethod.POST)
    public String delShoppingCart(int [] shopingId){
       try{
           for (int i=0;i<shopingId.length;i++){
               shopCartService.delShoppingCart(shopingId[i]);
           }
           return JSON.toJSONString("删除成功");
       }catch (Exception e){
           return JSON.toJSONString("删除失败");
       }
    }

}
